package com.changggou.gateway.filter;

import com.changggou.gateway.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author: zhengke
 * @date: 2020/12/13
 * @return:
 * @description: 请求校验token的过滤器  自定义的全局过滤器，所以要实现两大接口 GlobalFilter Ordered
 */

@Component
public class AuthFilter implements GlobalFilter,Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1 获取请求对象
        ServerHttpRequest request = exchange.getRequest();

        //2 获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        //3 获取请求中的URL
        String path = request.getURI().getPath();

        //4 判断请求路径是否是登录，如果登录就放行 path.contains("/admin/login/")
        if ("/system/admin/login".equals(path)){
            return chain.filter(exchange);
        }
        //5 如果请求路径非登录，那么继续校验，从请求头中获取token
        String token = request.getHeaders().getFirst("token");

        //6 判断token是否为空，如果为空返回401
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //7 token如果不为空，利用jwt解析token，如果解析失败返回401
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //8 如果解析token成功，放行请求
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
